package com.jerry.wschat.web.controller;

import com.jerry.wschat.web.security.MyUserDetails;
import com.jerry.wschat.web.security.UserLogin;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextImpl;

import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * @author Jerry.Wu
 * @description:
 * @date 2018/9/12 19:32
 */
public class BaseController<T, ID extends Serializable> {

    /**
     * 获取登录用户对象
     * @param session
     * @return
     */
    public UserLogin getCurrentUser(HttpSession session) {
        UserLogin userLogin = (UserLogin) session.getAttribute("userLogin");
        if (userLogin == null) {
            userLogin = new UserLogin();
            SecurityContextImpl securityContext = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
            MyUserDetails userDetails = (MyUserDetails)securityContext.getAuthentication().getPrincipal();
            BeanUtils.copyProperties(userDetails, userLogin);
            session.setAttribute("userLogin", userLogin);
        }
        return userLogin;
    }

}
